<?php
/**
 * Created by Administrator
 * User: longli
 * VX: isa1589518286
 * Date: 2020/08/12
 * Time: 10:51
 * @link http://www.lmterp.cn
 */

namespace app\common\service\platform;


use app\common\library\Tools;
use app\common\model\AccountSyncLog;
use app\common\model\Orders;
use app\common\model\OrdersTemp;
use app\common\service\orders\OrderService;
use think\facade\Log;

/**
 * 乐天德国接口服务
 * Class RakutenService
 * @package app\common\service\rakuten
 * @link http://webservice.rakuten.de/documentation/method/get_orders
 */
class RakutenDEService extends BasePlatformService
{
    public static $tokenField = [
        'required' => [ // 必填字段
            [
                'type' => 'text',
                'name' => 'key',
                'field' => 'key',
            ],
        ],
        'option' => [ // 可选字段
        ],
    ];

    /**
     * 获取订单列表
     * @param array $params 参数配置，默认抓取当天订单
     * <ul>
     * <li>string start_date 开始抓取的时间，默认为今天</li>
     * <li>string end_date 结束抓取的时间，默认为当前时间</li>
     * <li>int status 订单状态，默认为 editable</li>
     * <li>int page_size 分页大小，默认为 100 条</li>
     * </ul>
     * @param bool $replace 是否替换原有的订单，默认不替换
     * @date 2020/08/13
     * @author longli
     */
    public function getOrderList($params = [], $replace = false)
    {
        Log::info(sprintf("Rakuten 批量同步账号【%d】订单，请求参数: 【%s】", $this->getAccountId(), json_encode($params)));
        $startSyncTime = time();
        $url = $this->getBaseUrl() . "/merchants/orders/getOrders";
        $account = $this->getAccount();
        $page = 1; // 页码
        $args = [
            "key" => $account->token->key,
            "status" => !empty($params['status']) ? $params['status'] : 'editable',
            'created_from' => !empty($params['start_date']) ? $params['start_date'] : date('Y-m-d'),
            'created_to' => !empty($params['end_date']) ? $params['end_date'] : date('Y-m-d H:i:s'),
            'order' => 'created_desc',
            'per_page' => !empty($params['page_size']) ? $params['page_size'] : 100,
            'page' => & $page,
        ];
        do
        {
           $response = Tools::curlGet($url, $args);
            if(!$response['status'])
            {
                Log::info("Rakuten 请求订单列表异常【{$url}】, 参数: ". json_encode($args));
                break;
            }
            $xmlArray = Tools::xmlToArray($response['data']);
            if($xmlArray['success'] != 1)
            {
                Log::info(sprintf("Rakuten 订单接口异常【%d】, 参数: 【%s】, 响应: ",$url, json_encode($params), json_encode($xmlArray)));
                break;
            }
            if(empty($xmlArray['orders']['order'])) break;
            $orders = $xmlArray['orders']['order'];
            if(isset($orders[0])) // 多个订单
            {
                foreach($orders as $order)
                {
                    $this->pushOrderToTemp($order['order_no'], $order, $replace);
                }
            }
            else
            {
                $this->pushOrderToTemp($orders['order_no'], $orders, $replace);
            }
            $page++;
        }while($page <= $xmlArray['orders']['paging']['pages']);
        // 添加同步订单日志
        AccountSyncLog::addLog($this->getAccountId(), $startSyncTime, time(), $params);
    }

    /**
     * 获取产品详情
     * @param array $order 订单
     * @date 2020/08/14
     * @author longli
     * @return array|bool
     */
    public function getProduct($order)
    {
        $account = $this->getAccount();
        $ret = [];
        foreach($order['items'] as $item)
        {
            $productId = $item['product_id'];
            $url = $this->getBaseUrl() . "/merchants/products/getProducts?key={$account->token->key}&search={$productId}&search_field=product_id";
            $response = Tools::curlGet($url);
            if(!$response['status'])
            {
                Log::info("Rakuten 请求产品详情接口异常【{$url}】, 参数: null");
                return false;
            }
            $xml = Tools::xmlToArray($response['data']);
            if($xml['success'] != 1)
            {
                Log::info("Rakuten 请求产品详情接口异常【{$url}】, 响应: {$response['data']}");
                return false;
            }
            $ret[] = $xml;
        }
        return $ret;
    }

    /**
     * @inheritDoc
     */
    public function syncOrder(OrdersTemp $ordersTemp)
    {
        $data = $ordersTemp->order_info;
        $info = [];
        $oneSku = false;
        foreach($data['items']['item'] as $item)
        {
            if(!is_array($item))
            {
                $oneSku = true;
                $item = $data['items']['item'];
            }
            $info[] = [
                "item_id"       => $item['item_id'], // 商品 id
                "qty"           => $item['qty'], // 数量
                "return_qty"    => 0, // 取消数量
                "price"         => $item['price'], // 售价
                "platform_sku"  => $item['product_art_no'], // sku
                "name"          => $item['name'], // 产品名称
                'url'           => "", // 商品在线地址
            ];
            if($oneSku) break;
        }
        $platform = $this->getAccountById($ordersTemp->account_id)->platform;
        $address = $data['delivery_address'];
        $order = [
            "order_no"                  => $ordersTemp->order_no,
            "account_id"                => $ordersTemp->account_id,
            "platform_name"             => $platform->name, // 平台名称
            "order_platform_status"     => $data['status'], // 订单在平台的状态
            "buyer_gender"              => $address['gender'], // 客户性别
            "buyer_company"             => $address['company'], // 客户公司
            "buyer_first_name"          => $address['first_name'], // 客户名称
            "buyer_last_name"           => $address['last_name'], // 客户名称
            "buyer_phone"               => $data["client"]['phone'], // 电话
            "buyer_country"             => '', // 国家
            "buyer_country_code"        => $address['country'], // 国家编码
            "buyer_district"            => $address['street'], // 区
            "buyer_city"                => $address['city'], // 城市
            "buyer_post_code"           => $address['zip_code'], // 邮编
            "buyer_address_1"           => $address['address_add'], // 买家收货地址1
            "buyer_address_2"           => '', // 买家收货地址2
            "buyer_email"               => $data['client']['email'], // 买家邮箱
            "shipping_price"            => $data['shipping'], // 订单运费
            "order_source_create_time"  => $this->parseTimeToDate($data['created']), // 订单在平台生成的时间
            "latest_delivery_time"      => $this->parseTimeToDate($data['max_shipping_date']), // 最迟发货时间
            "payment_method"            => $data['payment'],
            "order_price"               => $data['total'], // 订单金额
            "total_price"               => $data['total'] + $data['shipping'], // 订单总金额
            "order_pay_time"            => null, // 订单支付时间
            "currency"                  => 'EUR', // 币种
            "invoice_detail"            => $data['invoice_no'], // 发票详情
            "track_num"                 => null, // 追踪号
            "platform_remark"           => null, // 买家备注信息
            "order_detail" => $info,
        ];
        return OrderService::getInstance()->addOrder($order);
    }

    public function markDelivery($orderIds = [])
    {
        foreach($this->getNeedMarkOrders($orderIds) as $order)
        {
            $args = [
                'order_no' => $order->order_no,
                'carrier' => 'Tracking-Link',
                'tracking_number' => $order->track_num,
                'tracking_url' => 'http://www.yuntrack.com/track/detail?id=' . $order->track_num
            ];
            $uri = http_build_query($args);
            $url = $this->getBaseUrl() . "/merchants/orders/setOrderShipped?key={$order->account->token->key}&{$uri}";
            $response = Tools::curlPost($url);
            if(!$response['status'])
            {
                Log::info(sprintf("RakutenDe 订单号【%s】标记请求异常，错误信息【%s】", $order->order_no, $response['info']));
                continue;
            }
            $xml = Tools::xmlToArray($response['data']);
            if(!isset($xml['success']) || $xml['success'] == -1)
            {
                Log::info(sprintf("RakutenDe 订单号【%s】标记失败，错误信息【%s】", $order->order_no, json_encode($xml)));
                continue;
            }
            $order->is_flag_sent = Orders::FLAG_SENT_YES;
            $order->sent_time = Tools::now();
            $order->save();
        }
    }
}